import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Products } from '../entities/products.entity';

@Injectable()
export class ProductsService {
  // 使用InjectRepository装饰器并引入Repository即可使用typeorm的操作
  constructor(
    @InjectRepository(Products)
    private readonly productsRepository: Repository<Products>,
  ) {}

  // 查询数据库产品数据
  // 获取所有用户数据列表（productsRepository.query()方法属于typeorm）
  async getList(): Promise<Products[]> {
    return await this.productsRepository.query('select * from products');
  }

  getProductsList(): any {
    return {
      code: 0,
      data: ['huawei233', 'changcheng', 'biyadi'],
    };
  }

  // get请求 -- 带参数
  getProductsById(id: number): any {
    let resJson: any = {};
    switch (id) {
      case 1:
        resJson = { id: 1, name: 'huewei', type: 'shouji' };
        break;
      case 2:
        resJson = { id: 2, name: 'changcheng', type: 'qiche' };
        break;
      case 3:
        resJson = { id: 3, name: 'biyadi', type: 'qiche' };
        break;
    }

    return resJson;
  }

  // Get请求-@Request()装饰器-动态参数id
  getProductsByIdRouter(id: number) {
    let resJson: any = {};
    switch (id) {
      case 1:
        resJson = { id: 1, name: 'huawei', type: 'shouji' };
        break;
      case 2:
        resJson = { id: 2, name: 'changcheng', type: 'qiche' };
        break;
      case 3:
        resJson = { id: 3, name: 'biyadi', type: 'qiche' };
        break;
    }
    return resJson;
  }

  // Get请求-@Param()装饰器-动态参数id，name
  getProductsByIdRouter2(id: number, name: string = 'huewei') {
    let resJson: any = {};
    switch (id) {
      case 1:
        resJson = { id: 1, name, type: 'shouji' };
        break;
      case 2:
        resJson = { id: 2, name, type: 'qiche' };
        break;
      case 3:
        resJson = { id: 3, name, type: 'qiche' };
        break;
    }
    return resJson;
  }

  // post请求
  addProducts() {
    return {
      code: 200,
      data: ['huewei2', 'changcheng2', 'biyadi2'],
      msg: '增加产品成功',
    };
  }

  addPostProducts(id: any) {
    const resJson: any = {
      code: 200,
      data: ['huwei3', 'changcheng3', 'biyadi3'],
      msg: '增加产品成功3',
    };
    switch (id) {
      case 1:
        resJson.data = ['huwei34'];
        break;
      case 2:
        resJson.data = ['changcheng34'];
        break;
      case 3:
        resJson.data = ['biyadi34'];
    }
    return resJson;
  }
}
